package com.diancan.modules.admin.admin;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diancan.common.Result;
import com.diancan.domain.Admin;
import com.diancan.domain.Restaurant;
import com.diancan.modules.admin.admin.admin.AdminService;
import com.diancan.modules.admin.restaurant.RestaurantService;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("admin")
@CrossOrigin
public class AdminController {
    private final AdminService adminService;
    private final RestaurantService restaurantService;

    public AdminController(AdminService adminService, RestaurantService restaurantService) {
        this.adminService = adminService;
        this.restaurantService = restaurantService;
    }

    // 登录
    @PostMapping("login")
    public Result login(@RequestBody Map<String, String> map) {
        JSONObject jsonObject = new JSONObject(map);
        String id = jsonObject.getString("id");
        String password = jsonObject.getString("password");
        if (id == null || "".equals(id) || password == null) {
            return Result.buildFailureResult("用户名或密码不能为空", false);
        }

        // 查询
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        Admin admin = adminService.getById(id);
        if (admin == null || !password.equals(admin.getPassword())) {
            return Result.buildFailureResult("用户名或密码错误", false);
        }
        StpUtil.login(id);
        return Result.buildSuccessResult("登录成功", true);
    }

    // 判断是否登录
    @GetMapping("isLogin")
    public Result isLogin() {
        return Result.buildSuccessResult(StpUtil.isLogin());
    }

    // 注销登录
    @GetMapping("logout")
    public void logout() {
        StpUtil.logout();
    }

    // 修改密码
    @PostMapping("updatePwd")
    public Result updatePwd(@RequestBody String newPwd) {
        Integer id = StpUtil.getLoginIdAsInt();
        Admin admin = adminService.getById(id);
        if (admin != null) {
            admin.setPassword(newPwd);
        }
        if (adminService.updateById(admin)) {
            return Result.buildSuccessResult(1);
        } else {
            return Result.buildFailureResult("修改失败");
        }
    }

    // 获取店铺信息
    @GetMapping("getRest")
    public Result getRest() {
        return Result.buildSuccessResult(restaurantService.list().get(0));
    }

    // 修改店铺信息
    @PostMapping("updateRest")
    public Result updateRest(@RequestBody Restaurant restaurant) {
        if (restaurant.getId() == null) {
            return Result.buildFailureResult("id为空");
        }
        if (restaurantService.updateById(restaurant)) {
            return Result.buildSuccessResult(1);
        } else {
            return Result.buildFailureResult("修改失败");
        }
    }


}
